package com.athena.crm.controller;

import java.util.*;
import java.util.stream.Collectors;

import com.athena.common.core.domain.entity.SysDept;
import com.athena.common.core.domain.entity.SysUser;
import com.athena.common.core.domain.model.LoginUser;
import com.athena.common.helper.LoginHelper;
import com.athena.common.utils.DateUtils;
import com.athena.crm.domain.bo.*;
import com.athena.crm.domain.vo.*;
import com.athena.crm.service.ICrmCluePoolService;
import com.athena.crm.service.ICrmClueService;
import com.athena.crm.service.ICrmClueFollrecordsService;
import com.athena.crm.service.ICrmCustomerService;
import com.athena.system.service.ISysDeptService;
import lombok.RequiredArgsConstructor;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.*;
import cn.dev33.satoken.annotation.SaCheckPermission;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.validation.annotation.Validated;
import com.athena.common.annotation.RepeatSubmit;
import com.athena.common.annotation.Log;
import com.athena.common.core.controller.BaseController;
import com.athena.common.core.domain.PageQuery;
import com.athena.common.core.domain.R;
import com.athena.common.core.validate.AddGroup;
import com.athena.common.core.validate.EditGroup;
import com.athena.common.enums.BusinessType;
import com.athena.common.utils.poi.ExcelUtil;
import com.athena.common.core.page.TableDataInfo;

/**
 * CRM线索
 *
 * @author ruoyi
 * @date 2023-07-02
 */
@Slf4j
@Validated
@RequiredArgsConstructor
@RestController
@RequestMapping("/crm/clue")
public class CrmClueController extends BaseController {

    private final ICrmClueService iCrmClueService;

    private final ICrmCluePoolService iCrmCluePoolService;

    private final ICrmCustomerService iCrmCustomerService;

    private final ISysDeptService sysDeptService;

    private final ICrmClueFollrecordsService ICrmClueFollrecordsService;

    /**
     * 查询CRM线索列表
     */
    @SaCheckPermission("crm:clue:list")
    @GetMapping("/list")
    public TableDataInfo<CrmClueVo> list(CrmClueBo bo, PageQuery pageQuery) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        return iCrmClueService.queryPageList(loginUser, bo, pageQuery);
    }

    /**
     * 导出CRM线索列表
     */
    @SaCheckPermission("crm:clue:export")
    @Log(title = "CRM线索", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(SysUser user, CrmClueBo bo, HttpServletResponse response) {
        LoginUser loginUser = LoginHelper.getLoginUser();
        List<CrmClueVo> list = iCrmClueService.queryList(loginUser, bo);
        ExcelUtil.exportExcel(list, "CRM线索", CrmClueVo.class, response);
    }

    /**
     * 获取CRM线索详细信息
     *
     * @param id 主键
     */
    @SaCheckPermission("crm:clue:query")
    @GetMapping("/{id}")
    public R<CrmClueVo> getInfo(@NotNull(message = "主键不能为空")
                                    @PathVariable Long id) {
        CrmClueVo crmClueVo = iCrmClueService.queryById(id);
        if (crmClueVo != null) {
            SysDept sysDept = sysDeptService.selectDeptById(crmClueVo.getDeptId());
            crmClueVo.setDeptName(sysDept.getDeptName());
            if (crmClueVo.getFormerDeptId() != null) {
                SysDept sysDept1 = sysDeptService.selectDeptById(crmClueVo.getFormerDeptId());
                crmClueVo.setFormerDeptName(sysDept1.getDeptName());
            }
        }
        //查询跟进记录
        CrmClueFollrecordsBo crmClueFollrecordsBo = new CrmClueFollrecordsBo();
        crmClueFollrecordsBo.setClueId(id + "");
        List<CrmClueFollrecordsVo> customerFollrecords = ICrmClueFollrecordsService.queryList(crmClueFollrecordsBo);
        List<CrmClueFollrecordsGroupVo> crmClueFollrecordsGroupVos = new ArrayList<>();
        for (CrmClueFollrecordsVo crmClueFollrecordsVo : customerFollrecords) {
            CrmClueFollrecordsGroupVo crmClueFollrecordsGroupVo = new CrmClueFollrecordsGroupVo();
            Date createTime = crmClueFollrecordsVo.getCreateTime();
            String createTimeStr = DateUtils.parseDateToStr("yyyy-MM-dd", createTime);
            Date key = DateUtils.dateTime("yyyy-MM-dd", createTimeStr);
            crmClueFollrecordsGroupVo.setDatekey(key);
            crmClueFollrecordsGroupVo.setCreateTime(createTime);
            crmClueFollrecordsGroupVo.setContent(crmClueFollrecordsVo.getFollowContent());
            crmClueFollrecordsGroupVos.add(crmClueFollrecordsGroupVo);
            log.info("==={}===={}===", crmClueFollrecordsVo.getClueId(), crmClueFollrecordsVo.getFollowContent());
        }
        List<CrmClueTimeLineVo> crmClueTimeLineVos1 = new ArrayList<>();
        Map<Date, List<CrmClueFollrecordsGroupVo>> groupMap = crmClueFollrecordsGroupVos.stream().filter(a -> a != null && a.getDatekey() != null).collect(Collectors.groupingBy(CrmClueFollrecordsGroupVo::getDatekey));
        Map<Date, List<CrmClueFollrecordsGroupVo>> sortedMap = groupMap.entrySet().stream()
            .sorted(Collections.reverseOrder(Map.Entry.comparingByKey()))
            .collect(
                Collectors.toMap(
                    Map.Entry::getKey,
                    Map.Entry::getValue,
                    (oldVal, newVal) -> oldVal,
                    LinkedHashMap::new
                )
            );
        sortedMap.forEach((key, value) -> {
            Date date = key;
            String yearmonth = DateUtils.getYearMonth(date);
            String dateStr = DateUtils.getDateStr(date);
            CrmClueTimeLineVo crmClueTimeLineVo1 = getCrmClueTimeLineVo(yearmonth, dateStr, value);
            crmClueTimeLineVos1.add(crmClueTimeLineVo1);
            log.info("Key: {}, Date: {}, createBy: {}, valueSize {}", key, date, key, value.size());
        });
        Map<String, List<CrmClueTimeLineMonthVo>> map = new HashMap<>();
        for (CrmClueTimeLineVo crmClueTimeLineVo : crmClueTimeLineVos1) {
            List<CrmClueTimeLineMonthVo> resultCrmClueTimeLineVos = map.get(crmClueTimeLineVo.getYearmonth());
            if (CollectionUtils.isEmpty(resultCrmClueTimeLineVos)) {
                resultCrmClueTimeLineVos = crmClueTimeLineVo.getBody();
                map.put(crmClueTimeLineVo.getYearmonth(), resultCrmClueTimeLineVos);
            } else {
                List<CrmClueTimeLineMonthVo> body = crmClueTimeLineVo.getBody();
                resultCrmClueTimeLineVos.addAll(body);
            }
            log.info("Key: {}, Date: {}, createBy: {}, valueSize {}", crmClueTimeLineVo.getYearmonth(), crmClueTimeLineVo.getBody().size());
        }
        List<CrmClueTimeLineVo> resultCrmClueTimeLineVos = new ArrayList<>();
        map.forEach((key, value) -> {
            CrmClueTimeLineVo crmClueTimeLineVo = new CrmClueTimeLineVo();
            crmClueTimeLineVo.setYearmonth(key);
            crmClueTimeLineVo.setBody(value);
            resultCrmClueTimeLineVos.add(crmClueTimeLineVo);
        });
        resultCrmClueTimeLineVos.sort(Comparator.comparing(CrmClueTimeLineVo::getYearmonth).reversed());
        crmClueVo.setCrmClueTimeLineVos(resultCrmClueTimeLineVos);
        return R.ok(crmClueVo);
    }

    private CrmClueTimeLineVo getCrmClueTimeLineVo(String yearmonth, String date, List<CrmClueFollrecordsGroupVo> groupVos) {
        CrmClueTimeLineVo crmClueTimeLineVo1 = new CrmClueTimeLineVo();
        crmClueTimeLineVo1.setYearmonth(yearmonth);
        List<CrmClueTimeLineMonthVo> crmClueTimeLineMonthVos = new ArrayList<>();
        CrmClueTimeLineMonthVo crmClueTimeLineMonthVo1 = getCrmClueTimeLineMonthVo(date, groupVos);
        crmClueTimeLineMonthVos.add(crmClueTimeLineMonthVo1);
        crmClueTimeLineVo1.setBody(crmClueTimeLineMonthVos);
        return crmClueTimeLineVo1;
    }

    private CrmClueTimeLineMonthVo getCrmClueTimeLineMonthVo(String date, List<CrmClueFollrecordsGroupVo> groupVos) {
        CrmClueTimeLineMonthVo crmClueTimeLineMonthVo1 = new CrmClueTimeLineMonthVo();
        crmClueTimeLineMonthVo1.setDate(date);
        List<CrmClueTimeLineMonthChildrenVo> monthChildren = getCrmClueTimeLineMonthChildrenVos(groupVos);
        crmClueTimeLineMonthVo1.setChildren(monthChildren);
        return crmClueTimeLineMonthVo1;
    }

    private List<CrmClueTimeLineMonthChildrenVo> getCrmClueTimeLineMonthChildrenVos(List<CrmClueFollrecordsGroupVo> groupVos) {
        List<CrmClueTimeLineMonthChildrenVo> monthChildren = new ArrayList<>();
        for (CrmClueFollrecordsGroupVo crmClueFollrecordsGroupVo : groupVos) {
            CrmClueTimeLineMonthChildrenVo crmClueTimeLineMonthChildrenVo = new CrmClueTimeLineMonthChildrenVo();
            crmClueTimeLineMonthChildrenVo.setTime(DateUtils.parseDateToStr("HH:mm:ss", crmClueFollrecordsGroupVo.getCreateTime()));
            crmClueTimeLineMonthChildrenVo.setTitle(crmClueFollrecordsGroupVo.getContent());
            monthChildren.add(crmClueTimeLineMonthChildrenVo);
        }
        return monthChildren;
    }

    /**
     * 新增CRM线索
     */
    @SaCheckPermission("crm:clue:add")
    @Log(title = "CRM线索", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping()
    public R<Void> add(@Validated(AddGroup.class) @RequestBody CrmClueBo bo) {
        return toAjax(iCrmClueService.insertByBo(bo));
    }

    /**
     * 修改CRM线索
     */
    @SaCheckPermission("crm:clue:edit")
    @Log(title = "CRM线索", businessType = BusinessType.UPDATE)
    @RepeatSubmit()
    @PutMapping()
    public R<Void> edit(@Validated(EditGroup.class) @RequestBody CrmClueBo bo) {
        return toAjax(iCrmClueService.updateByBo(bo));
    }

    /**
     * 删除CRM线索
     *
     * @param ids 主键串
     */
    @SaCheckPermission("crm:clue:remove")
    @Log(title = "CRM线索", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public R<Void> remove(@NotEmpty(message = "主键不能为空")
                          @PathVariable Long[] ids) {
        return toAjax(iCrmClueService.deleteWithValidByIds(Arrays.asList(ids), true));
    }

    /**
     * 线索转线索池
     */
    @SaCheckPermission("crm:clueFollrecords:add")
    @Log(title = "线索转线索池", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/transferClueToCluePool")
    public R<Void> transferClueToCluePool(@Validated(AddGroup.class) @RequestBody CrmClueTransferBo bbo) {
        return toAjax(iCrmCluePoolService.insertByBbo(bbo));
    }

    /**
     * 线索转客户
     */
    @SaCheckPermission("crm:clueFollrecords:add")
    @Log(title = "线索转客户", businessType = BusinessType.INSERT)
    @RepeatSubmit()
    @PostMapping("/transferClueToCustomer")
    public R<Void> transferClueToCustomer(@Validated(AddGroup.class) @RequestBody CrmClueTransferCustomerBo bbo) {
        return toAjax(iCrmCustomerService.clueTransferCustomer(bbo));
    }

}
